package in.sv.enge.activity;

import in.sv.android.enge.R;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import android.app.Activity;
import android.content.Context;
import android.location.Address;
import android.location.Criteria;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.view.View;
import android.widget.Button;

public class EngeActivity extends Activity {

	private static final int MAX_SMS_MESSAGE_LENGTH = 160;

	private StringBuilder mSB = null;
	
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
		Criteria criteria = new Criteria();
		criteria.setAccuracy(Criteria.ACCURACY_FINE);
		criteria.setPowerRequirement(Criteria.POWER_LOW);
		String locationprovider = locationManager.getBestProvider(criteria,
				true);
		Location mLocation = locationManager
				.getLastKnownLocation(locationprovider);
		List<Address> addresses;
		Geocoder mGC = new Geocoder(this, Locale.ENGLISH);
		mSB = new StringBuilder("Address:\n");
		try {
			addresses = mGC.getFromLocation(mLocation.getLatitude(),
					mLocation.getLongitude(), 1);
			if (addresses != null) {
				Address currentAddr = addresses.get(0);

				for (int i = 0; i < currentAddr.getMaxAddressLineIndex(); i++) {
					mSB.append(currentAddr.getAddressLine(i)).append("\n");
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		}

		((Button) findViewById(R.id.btnClickMe))
				.setOnClickListener(onButtonClick);

	}

	private View.OnClickListener onButtonClick = new View.OnClickListener() {
		@Override
		public void onClick(View v) {
			switch (v.getId()) {
			case R.id.btnClickMe: {
				String phonenumber = "9916102426";
				String message = mSB.toString();
				// String message = mSB;
				boolean isBinary = false;

				sendSms(phonenumber, message, isBinary);

				break;
			}
			}
		}

		private void sendSms(String phonenumber, String message,
				boolean isBinary) {
			SmsManager manager = SmsManager.getDefault();

			int length = message.length();
			// Acquire a reference to the system Location Manager

			if (length > MAX_SMS_MESSAGE_LENGTH) {
				ArrayList<String> messagelist = manager.divideMessage(message);

				manager.sendMultipartTextMessage(phonenumber, null,
						messagelist, null, null);
			} else {
				manager.sendTextMessage(phonenumber, null, message, null, null);
			}

		}
	};

}